package com.zhoux.server.demo;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

public class Processer extends Thread{
	
	private Socket socket=null;
	
	private FileInputStream fin=null;
	
	private InputStream in;
	
	private PrintStream out;
	
	private Map<String,String> requestMap=new HashMap<String,String>();
	
	private final static String WebRoot="C:\\WebRoot\\";
	public Processer(Socket socket) {
		this.socket=socket;
		try {
			in=socket.getInputStream();
			out=new PrintStream(socket.getOutputStream());
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
	
	@Override
	public void run() {
		getRequestData(in);
		sendFile(requestMap.get("fileName"));
	}
	
	public void getRequestData(InputStream in){
		BufferedReader br=new BufferedReader(new InputStreamReader(in));
		try {
			String mess=br.readLine();
			System.out.println("requestPath:"+mess);
			String[] contents=mess.split("");
			if(contents.length!=3){
				retErrorMessage("400"," Request is Errors!");
				return ;
			}
			requestMap.put("code", contents[0]);
			requestMap.put("fileName", contents[1]);
			requestMap.put("httpVersion", contents[2]);
			System.out.println("code："+ contents[0]+";fileName"+contents[1]);
		} catch (IOException e) {
			System.out.println("system is wrong!");
		}finally {
			try {
				br.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
	}
	
	
	
	public void sendFile(String fileName){
		File file=new File(Processer.WebRoot+fileName);
		if(!file.exists()){
			retErrorMessage("404","Conn't found this file!");
		}
		try {
			System.out.println("fileName:"+fileName);
			fin=new FileInputStream(file);
			byte retData[]=new byte[(int)file.length()];
			fin.read(retData);
			out.println(requestMap.get("httpVersion")+"200"+requestMap.get("fileName"));
			out.println("content-length:"+retData.length);
			out.println();
			out.write(retData);
			out.flush();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			out.close();
			if(fin!=null){
				try {
					fin.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	
	public void retErrorMessage(String errorCode,String errorMessage){
		out.println(requestMap.get("httpVersion")+errorCode+errorMessage);
	}

}
